<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" clearable v-model="queryInfo.query" @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible=!addDialogVisible">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户表格 -->
      <el-table :data="userList" border style="width: 100%" stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <!-- 状态开关 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="mg_state" label="操作">
          <!-- 操作相关按钮 -->
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUserById(scope.row.id)"
            ></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showSetRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="this.queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <!-- 内容主体区 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户的对话框 -->
    <el-dialog @close="editDialogClose" title="修改用户" :visible.sync="editDialogVisible" width="50%">
      <el-form label-width="100px" :model="editForm" :rules="editFormRules" ref="editForm">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色用的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClose"
    >
      <p>当前的用户：{{userInfo.username}}</p>
      <p>当前的角色：{{userInfo.role_name}}</p>
      <p>
        请选择角色
        <el-select v-model="selectdRoleId" placeholder="请选择角色">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogClose = false">取 消</el-button>
        <el-button type="primary" @click="setRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  // eslint-disable-next-line space-before-function-paren
  data () {
    // 验证邮箱规则
    var checkEmail = (rule, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }
    // 验证手机号规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

      if (regMobile.test(value)) {
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }
    return {
      // 获取接口参数，最好写在data中，后期维护比较容易
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 用户列表
      userList: [],
      // 用户总数
      total: 0,
      // 分配角色对话框的状态控制
      setRoleDialogVisible: false,
      // 添加用户的对话框的状态
      addDialogVisible: false,
      // 修改用户的对话框的状态
      editDialogVisible: false,
      // 添加用户用到的表单
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 查询到用户对象
      editForm: {
        id: '',
        email: '',
        mobile: ''
      },
      // 当需要分配角色的用户的具体信息
      userInfo: {},
      // 所有角色数据列表
      rolesList: [],
      // 分配角色的选择
      selectdRoleId: '',
      // 添加用户用到的验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          {
            validator: checkMobile,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  // eslint-disable-next-line space-before-function-paren
  created () {
    // 获取用户列表
    this.getUserList()
    // console.log(this.$scopedSlots)
  },
  methods: {
    // eslint-disable-next-line space-before-function-paren
    async getUserList () {
      console.log(this.queryInfo)

      const { data: res } = await this.$http.get('/users', {
        // get请求参数写在params中
        params: this.queryInfo
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.total = res.data.total
      this.userList = res.data.users
    },
    // 当表格的容量改变时
    // eslint-disable-next-line space-before-function-paren
    handleSizeChange (val) {
      // 监听pagesize改变的事件，
      console.log(val)
      // 当显示的数量改变时

      this.queryInfo.pagesize = val
      this.getUserList()
    },
    // 当页码改变时
    // eslint-disable-next-line space-before-function-paren
    handleCurrentChange (val) {
      console.log(val)
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    // 改变开关用户状态
    // eslint-disable-next-line space-before-function-paren
    async userStateChange (userInfo) {
      // userInfo的意思是表格的行数据，注意：表格的行数据是展示出来的数据，不是最初渲染的数据
      console.log(userInfo.mg_state)
      // eslint-disable-next-line no-unused-vars
      const { data: res } = await this.$http.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        // 当点击时开关状态已经改变，但是没有成功在数据库中更改，所以要改回来
        userInfo.mg_state = !userInfo.mg_state
        return this.$message.error('更改状态失败')
      }
      this.$message.success('更改状态成功')
    },
    // 添加用户对话框关闭的时候触发
    // eslint-disable-next-line space-before-function-paren
    addDialogClose () {
      this.$refs.addForm.resetFields()
    },
    // 新增用户对话框中的确定按钮
    // eslint-disable-next-line space-before-function-paren
    addUser () {
      this.$refs.addForm.validate(async valid => {
        // 没有通过验证，弹出错误提示框
        if (valid !== true) {
          // eslint-disable-next-line no-useless-return
          return
        }
        // 通过验证，发送请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('添加用户失败')
        this.$message.success('添加用户成功')
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        // 重新获取用户列表
        this.getUserList()
        // console.log(res)
      })
    },
    // eslint-disable-next-line space-before-function-paren
    async showEditDialog (id) {
      const { data: res } = await this.$http.get('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('查询用户失败')
      // 查询成功
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // eslint-disable-next-line space-before-function-paren
    editDialogClose () {
      this.$refs.editForm.resetFields()
    },
    // eslint-disable-next-line space-before-function-paren
    editUser () {
      this.$refs.editForm.validate(async valid => {
        if (valid !== true) {
          // eslint-disable-next-line no-useless-return
          return
        }
        // 通过验证,发起请求
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          this.editForm
        )
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户失败')
        }

        this.editDialogVisible = false
        this.getUserList()
        this.$message.success('用户修改成功')
      })
    },
    // 点击删除按钮时setRoleDialogVisible
    // eslint-disable-next-line space-before-function-paren
    async deleteUserById (id) {
      const removeUserById = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      // 如果用户确认删除，则返回值为字符串confirm
      // 如果用户取消了删除，则返回值为字符串cancel
      console.log(removeUserById)

      if (removeUserById !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败')
      this.$message.success('删除用户成功')
      this.getUserList()
    },
    // 分配角色对话框
    async showSetRoleDialog (userInfo) {
      this.userInfo = userInfo
      // 获取角色列表
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 分配角色对话框中的确定按钮
    async setRole () {
      if (!this.selectdRoleId) {
        return this.$message.error('请选择用户角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectdRoleId
      })
      console.log(res)

      if (res.meta.status !== 200) return this.$message.error('分配角色失败')
      this.$message.success('分配角色成功')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 关闭分配角色对话框
    setRoleDialogClose () {
      this.selectdRoleId = ''
      this.userInfo = ''
      this.setRoleDialogVisible = false
    }

  }
}
</script>
<style lang="less" scoped>
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
</style>
